package com.chuangke.mds.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.chuangke.admin.entity.SysUser;
import com.chuangke.context.service.ContextService;
import com.chuangke.mds.dao.TechnologyProcessProcedureDao;
import com.chuangke.mds.dao.mapper.TechnologyProcessProcedureNodeSimulateMapper;
import com.chuangke.mds.entity.TechnologyProcessProcedure;
import com.chuangke.system.entity.SysAttachment;
import com.chuangke.system.service.SysAttachmentService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.trans.annotation.TransResult;
import com.chuangke.mds.dao.TechnologyProcessProcedureNodeSimulateDao;
import com.chuangke.mds.entity.TechnologyProcessProcedureNodeSimulate;
import com.chuangke.mds.service.TechnologyProcessProcedureNodeSimulateService;

@Service
@Transactional(rollbackFor = Throwable.class)
public class TechnologyProcessProcedureNodeSimulateImpl implements TechnologyProcessProcedureNodeSimulateService {
	private static final Logger logger = LoggerFactory.getLogger(KnowledgeServiceImpl.class);
	@Autowired
	private TechnologyProcessProcedureNodeSimulateDao simulateDao;
	@Autowired
	private TechnologyProcessProcedureDao procedureDao;
	@Autowired
	private TechnologyProcessProcedureNodeSimulateMapper simulateMapper;
	@Autowired
	private SysAttachmentService sysAttachmentService;
	@Autowired
	private ContextService contextService;
	@Override
	public String save(TechnologyProcessProcedureNodeSimulate model) {
		return saveOrUpdate(model);
	}
	
	@Override
	public void update(TechnologyProcessProcedureNodeSimulate model) {
		saveOrUpdate(model);
	}

	@Override
	public String saveOrUpdate(TechnologyProcessProcedureNodeSimulate model) {
		doSave(model) ;
		return model.getId() ;
	}
	
	private void doSave(TechnologyProcessProcedureNodeSimulate model) {
		if(StringUtils.isEmpty(model.getId())){
			model.setId(IdManager.nextId());
		}
		simulateDao.saveOrUpdate(model) ;
		//存储附件
		List<SysAttachment> attachmentList = model.getSimulationFileList();
		if(attachmentList!=null&&attachmentList.size()>0){
			attachmentList.forEach(attachment -> {
				attachment.setSubjectId(model.getId());
				attachment.setStatus("1");
			});
			sysAttachmentService.removeBySubjectId(model.getId());
			sysAttachmentService.saveOrUpdateBatch(attachmentList);
		}
		UpdateWrapper<TechnologyProcessProcedure> updateWrapper = new UpdateWrapper<>();
		updateWrapper.lambda().set(TechnologyProcessProcedure::getSimulateId, model.getId());
		updateWrapper.lambda().eq(TechnologyProcessProcedure::getId, model.getProcedureId());
		procedureDao.update(updateWrapper);
	}

	@Override
	public void delete(List<String> billIds) {
		QueryWrapper<TechnologyProcessProcedureNodeSimulate> qw = new QueryWrapper<TechnologyProcessProcedureNodeSimulate>() ;
		qw.lambda().in(TechnologyProcessProcedureNodeSimulate::getId, billIds) ;
        simulateDao.remove(new QueryWrapper<TechnologyProcessProcedureNodeSimulate>().lambda().in(TechnologyProcessProcedureNodeSimulate::getId, billIds));
	}

	@Override
	@TransResult
	public TechnologyProcessProcedureNodeSimulate load(String billId) {
		TechnologyProcessProcedureNodeSimulate simulate = null;
//		if (StringUtils.isEmpty(billId)){
//			simulate = new TechnologyProcessProcedureNodeSimulate();
//		}else{
//			simulate = simulateDao.getById(billId) ;
//		}
		simulate = simulateMapper.loadInfoById(billId);
		//仿真报告
		List<SysAttachment> simulationFileList = sysAttachmentService.getListBySubjectId(billId);
		simulate.setSimulationFileList(simulationFileList);
		return simulate;
	}
	@TransResult
	@Override
	public TechnologyProcessProcedureNodeSimulate loadForOrigin(String billId) {
		TechnologyProcessProcedureNodeSimulate simulate = null;
		if (StringUtils.isEmpty(billId)){
			simulate = new TechnologyProcessProcedureNodeSimulate();
		}else{
			simulate = simulateDao.getById(billId) ;
		}
		return simulate;
	}
	@Override
	@TransResult
	public TechnologyProcessProcedureNodeSimulate loadInfoByProcedure( Map<String, Object> params) {
		String procedureId = params.get("procedureId").toString();
		String processId = params.get("processId").toString();
		TechnologyProcessProcedureNodeSimulate simulate = null;
		simulate = simulateMapper.loadInfoByProcedure(processId,procedureId);
		return simulate;
	}

	@Override
	@TransResult
	public IPage<TechnologyProcessProcedureNodeSimulate> page(CkPageQuery page) {
		IPage<TechnologyProcessProcedureNodeSimulate> result = null;
		String processId = page.getAsString("processId");
		String processName = page.getAsString("processName");
		String procedureName = page.getAsString("procedureName");
		String productMx = page.getAsString("productMx");
		String status = page.getAsString("status");
		String start = page.getAsString("start");
		String end = page.getAsString("end");
		SysUser user= contextService.getCurrentUser();
		String userId = user.getId();
		String userDeptId = "";
		if (!"admin".equals(userId)) {
			userDeptId = user.getDeptId();
		}

		result = simulateMapper.getPage(page.getPage(),processId, processName, procedureName, productMx, status, start, end,userDeptId);
		return result;
	}
	//之前的加载
	@Override
	public IPage<TechnologyProcessProcedureNodeSimulate> loadByNode(CkPageQuery page) {
		QueryWrapper<TechnologyProcessProcedureNodeSimulate> qw = new QueryWrapper<>();
		qw.lambda().eq(TechnologyProcessProcedureNodeSimulate::getProcessId, page.getAsString("processId"))
				.eq(TechnologyProcessProcedureNodeSimulate::getProcedureId, page.getAsString("procedureId"))
				.eq(TechnologyProcessProcedureNodeSimulate::getNodeId,page.getAsString("nodeId") );
		return simulateDao.page(page.getPage(),qw);
	}

	@Override
	public List<TechnologyProcessProcedureNodeSimulate> loadByBatchId(List<String> billIds) {
		if(CollectionUtils.isEmpty(billIds)) {
			return new ArrayList<>() ;
		}
		QueryWrapper<TechnologyProcessProcedureNodeSimulate> qw = new QueryWrapper<>();
		qw.lambda().in(TechnologyProcessProcedureNodeSimulate::getId, billIds);
		return simulateDao.list(qw);
	}
	//副应用的推送
	@Override
	public String updateInfoByPython(TechnologyProcessProcedureNodeSimulate simulate) {
		UpdateWrapper<TechnologyProcessProcedureNodeSimulate> qw = new UpdateWrapper<>();
		qw.lambda().set(TechnologyProcessProcedureNodeSimulate::getExecuteStatus, simulate.getExecuteStatus());
		qw.lambda().set(TechnologyProcessProcedureNodeSimulate::getStatus, simulate.getStatus());
		if (!StringUtils.isEmpty(simulate.getPythonLog())){
			qw.lambda().set(TechnologyProcessProcedureNodeSimulate::getPythonLog, simulate.getPythonLog());
		}
		if (!StringUtils.isEmpty(simulate.getExecuteEnd())){
			qw.lambda().set(TechnologyProcessProcedureNodeSimulate::getExecuteEnd, simulate.getExecuteEnd());
		}
		if (!StringUtils.isEmpty(simulate.getExecuteStart())){
			qw.lambda().set(TechnologyProcessProcedureNodeSimulate::getExecuteStart, simulate.getExecuteStart());
		}
		qw.lambda().eq(TechnologyProcessProcedureNodeSimulate::getId, simulate.getId());
		simulateDao.update(qw);
		return simulate.getId();
	}
	//页面获取的
	@Override
	public String getPythonLog(String id) {
		UpdateWrapper<TechnologyProcessProcedureNodeSimulate> qw = new UpdateWrapper<>();
		qw.lambda().eq(TechnologyProcessProcedureNodeSimulate::getId, id);
		TechnologyProcessProcedureNodeSimulate simulate = simulateDao.getOne(qw);
		return simulate.getPythonLog();
	}


	@Override
	public List<TechnologyProcessProcedureNodeSimulate> getHomePageData() {
		SysUser user= contextService.getCurrentUser();
		String userId = user.getId();
		List<TechnologyProcessProcedureNodeSimulate> list = simulateMapper.getHomeSimPageData(userId);
		try {
			list.forEach(simulate -> {
				simulate.setSimulateTypeName("");
				String productMx = simulate.getProductMx();
				String simulateType = simulate.getSimulateType();
				if (!StringUtils.isEmpty(productMx)){
					List<String> productMxList = Arrays.asList(productMx.split(";"));
					for (String productMxEntity : productMxList){
						String[] productMxArr = productMxEntity.split(":");
						if(simulateType.equals(productMxArr[0])){
							simulate.setSimulateTypeName(productMxArr[1]);
							break;
						}
					}
				}
			});
		} catch (Exception e) {
			logger.error("获取首页数据【仿真任务】异常",e);
		}
		return list;
	}
}
